package com.xiaobai.demo;

import com.xiaobai.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class ThreadJoinUp {
    static int r = 0;
    static int r1 = 0;
    static int r2 = 0;

    public static void main(String[] args) {
        test2();
    }

    public static void test1() throws InterruptedException {
        log.debug("start");
        Thread t1 = new Thread(() -> {
            log.debug("t1 start");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            log.debug("t1 end");
            r = 10;
        }, "t1");
        t1.start();
        log.debug("result is {}", r);
        log.debug("end");
        t1.join();
        log.debug("result is join {}", r);
        log.debug("end join");
    }

    public static void test2()  {
        Thread t1 = new Thread(() -> {
            ThreadUtil.sleep(1);
            r1 = 10;
        },"t1");
        Thread t2 = new Thread(() -> {
            ThreadUtil.sleep(2);
            r2 = 20;
        },"t2");
        t1.start();
        t2.start();
        log.debug("join begin");
        try {
            t1.join();
            log.debug("t1 join end");
            t2.join();
            log.debug("t2 join end");
        } catch (InterruptedException e) {
            log.error("{}被打断了",Thread.currentThread().getName());
        }
        log.info("result is {},{}",r1,r2);
    }

    public static void test3()  {
        Thread t3 = new Thread(() -> {
            ThreadUtil.sleep(1); //会把线程打断的标记清空，也就是重置为false
            r1 = 10;
        },"t1");
        t3.start();
        try {
            //若等待的时间长于线程执行时间，则线程会继续执行，不会被中断
            t3.join(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }
}
